package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.cacheable.Cacheable;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;

import com.itheima.exceptions.BusinessException;
import com.itheima.pojo.Diary;

import com.itheima.service.DiaryService;

import com.itheima.utils.POIUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("diary")
public class DiaryController {

    @Reference(version = "1.0.0")
    private DiaryService diaryService;

    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = diaryService.findPage(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @Cacheable(expire = 600)
    @GetMapping("findAll")
    @PreAuthorize("hasAuthority('CHECKGROUP_QUERY')")
    public Result findAll(){
        List<Diary> list = diaryService.findAll();
        System.out.println("这里是查询所有随访日记，我从数据库查询了！");
        return new Result(true,"查询成功",list);
    }
    @RequestMapping("add")
    @PreAuthorize("hasAuthority('CHECKGROUP_ADD')")
    public Result add(@RequestBody Diary diary, Errors errors){
        if(errors.hasErrors()){
            StringBuilder msg = new StringBuilder();
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (int i = 0; i < fieldErrors.size(); i++) {
                if(i!=fieldErrors.size()-1) {
                    msg.append(fieldErrors.get(i).getDefaultMessage()).append(",");
                }else {
                    msg.append(fieldErrors.get(i).getDefaultMessage()).append("!");
                }
            }
            return new Result(false, msg.toString());
        }
        //调用业务层添加方法
        diaryService.add(diary);
        //返回操作结果
        return new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
    }
    @RequestMapping("update")
    public Result update(@RequestBody Diary diary){
        //调用业务层修改方法
        diaryService.update(diary);
        //返回操作结果
        return new Result(true, MessageConstant.EDIT_CHECKITEM_SUCCESS);
    }

    @GetMapping("delete/{id}")
    public Result delete(@PathVariable int id){
        //调用业务层删除方法
        diaryService.delete(id);
        //返回操作结果
        return new Result(true, MessageConstant.DELETE_CHECKITEM_SUCCESS);
    }

    @RequestMapping("upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            List<String[]> strings = POIUtils.readExcel(excelFile);
            List<Diary> diarys = new ArrayList<>();
            for (String[] string : strings) {

                //回访日期
                Date returnDate = new SimpleDateFormat("yyyy/MM/dd").parse(string[0]);

                Diary diary = new Diary();
                diary.setReturnDate(returnDate);
                diary.setMember(string[1]);
                diary.setVisitor(string[2]);
                diary.setWay(string[3]);
                diary.setContent(string[4]);
                diary.setFeedback(string[5]);
                diary.setProcess(string[6]);
                diarys.add(diary);
            }

            diaryService.upload(diarys);
            //导入成功返回结果
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            throw new BusinessException("上传文件解析错误，请检查文件内容");
        }
    }

}
